/**
 * 
 */
package com.rtsp.tool.snatch;

import org.bytedeco.javacv.*;
//import org.bytedeco.opencv.opencv_core.Mat;

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

/**
 * rtsp 流抓图
 * 
 * @author w.weizhen
 *
 */
public class RtspSnatch {
	// 视频链接
	private static String rtsp_url = "rtsp://admin:88888888b@192.168.12.105:554/Streaming/Channels/101";
	// 工作目录
	private static final String user_dir = System.getProperty("user.dir") + File.separator;
	private static final String data_path = user_dir + "data" + File.separator;
	
	/**
	 * @param args
	 */
	public static void main(String[] args) 
	{
		File data_file = new File(data_path);
		if(!data_file.exists())
		{
			data_file.mkdir();
		}
		work();
	}
	
	private static void work()
	{
		try {
			FFmpegFrameGrabber grabber = FFmpegFrameGrabber.createDefault(rtsp_url);
			grabber.setOption("rtsp_transport", "tcp"); // 使用tcp的方式，不然会丢包很严重
			grabber.setImageWidth(1280);
			grabber.setImageHeight(720);
			System.out.println("grabber start");
			grabber.start();
			
//			//1.播放视频
//			CanvasFrame canvasFrame = new CanvasFrame("摄像机");
//			canvasFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//			canvasFrame.setAlwaysOnTop(true);
//			OpenCVFrameConverter.ToMat converter = new OpenCVFrameConverter.ToMat();
//			while (true) {
//				Frame frame = grabber.grabImage();
//				Mat mat = converter.convertToMat(frame);
//				canvasFrame.showImage(frame);
//			}
			
			// 2.帧截图
			while (true) {
				Frame frame = grabber.grabImage();
				if (frame != null) {
					File outPut = new File(data_path + System.currentTimeMillis() + ".jpeg");
					ImageIO.write(FrameToBufferedImage(frame), "jpeg", outPut);
//					 grabber.stop();
//					 grabber.release();
					System.out.println("图片已保存");
					// break;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 创建BufferedImage对象
	 */
	public static BufferedImage FrameToBufferedImage(Frame frame) {
		Java2DFrameConverter converter = new Java2DFrameConverter();
		BufferedImage bufferedImage = converter.getBufferedImage(frame);
//		bufferedImage=rotateClockwise90(bufferedImage);//将图片旋转90度
		return bufferedImage;
	}

	/**
	 * 处理图片，将图片旋转90度。
	 */
	public static BufferedImage rotateClockwise90(BufferedImage bi) {
		int width = bi.getWidth();
		int height = bi.getHeight();
		BufferedImage bufferedImage = new BufferedImage(height, width, bi.getType());
		for (int i = 0; i < width; i++)
			for (int j = 0; j < height; j++)
				bufferedImage.setRGB(j, i, bi.getRGB(i, j));
		return bufferedImage;
	}

}